export const draggable = {
  inserted: function(el, binding) {
    el.style.cursor = "move"
    el.onmousedown = function(e) {
      const time1 = new Date()
      const disx = e.pageX - el.offsetLeft
      const disy = e.pageY - el.offsetTop
      document.onmousemove = function(e) {
        let x = e.pageX - disx
        let y = e.pageY - disy
        const maxX = document.body.clientWidth - parseInt(window.getComputedStyle(el).width)
        const maxY = document.body.clientHeight - parseInt(window.getComputedStyle(el).height)
        if (x < 0) {
          x = 0
        } else if (x > maxX) {
          x = maxX
        }

        if (y < 0) {
          y = 0
        } else if (y > maxY) {
          y = maxY
        }

        el.style.left = x + "px"
        el.style.top = y + "px"
      }
      document.onmouseup = function(e) {
        const time2 = new Date
        if (time2 - time1 < 200) {
          binding.value&&binding.value()
        }
        document.onmousemove = document.onmouseup = null
      }
    }

    const width = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth
    const height = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight
    let time
    el.ontouchstart = function(event) {
      event.stopPropagation()
      event.preventDefault()
      time = new Date()
    }
    el.ontouchmove = function(event) {
      event.stopPropagation()
      event.preventDefault()
      const x = event.touches[0].clientX - (el.clientWidth / 2)
      const y = event.touches[0].clientY - (el.clientHeight / 2)

      const endPositionX = x < 0 ? 0 : x > (width - el.clientWidth) ? (width - el.clientWidth) : x
      const endPositionY = y < 0 ? 0 : y > (height - el.clientHeight) ? (height - el.clientHeight) : y
      el.style.top = endPositionY + "px"
      el.style.left = endPositionX + "px"
    }
    el.ontouchend = function() {
      //超过200毫秒未移动证明他是点击行为
      if ((new Date() - time) < 200) {
        binding.value&&binding.value()
      }
    }
  }
}
